package org.server.http.core;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;

import org.server.http.Servlet;
import org.server.http.conf.URLMappingConfig;

/**
 * 定位servlet 并执行
 * 
 * @author Admin
 * 
 */
public class ServletFiexdExector {
	// 路径映射
	private SwapStream current = null;
	private Socket socket;

	/**
	 * 构建servlet处理器
	 * 
	 * @param sock
	 * @throws IOException
	 */
	public ServletFiexdExector(Socket sock) throws IOException {
		socket = sock;
		current = new SwapStream(sock, 5000);
	}

	/**
	 * 执行servlet 方法
	 * 
	 * @param servlet
	 * @param method
	 * @throws IOException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public void execute() throws IOException {
		// 接受请求
		AcceptRequest accept = new AcceptRequest(current);
		if (accept.validationRequestHeader()) {
			HttpResponse response = new HttpResponse();
			response.setContentType("text/html");
			response.setCharset("utf-8");
			HttpRequest request = accept.getRequest();
			// 远程地址
			accept.setRemoteAddr(socket.getInetAddress().getHostAddress());
			// 获取servlet
			String servlet_uri = URLMappingConfig.getServletURI(request.getServletPath());
			Servlet servlet = URLMappingConfig.getMappServlet(servlet_uri);
			if (servlet != null) {
				// 默认响应码
				response.setStatus(200);
				request.setServletURI(servlet_uri);
				// 提交给方法执行
				if ("POST".equals(request.getMethod())) {
					// 执行post 方法
					servlet.post(request, response);
				} else {
					// 执行get方法
					servlet.get(request, response);
				}
			}
			// 构建响应
			BuilderHttpResponseHeader header = new BuilderHttpResponseHeader(response);
			// 输出响应头
			current.write(header.responseHeaderStream().toByteArray());
			// 输出响应内容
			current.write(response.getOutputStream().toByteArray());
		}
	}

	/**
	 * 关闭资源
	 */
	public void close() {
		try {
			current.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}
	}
}
